﻿
using SearchServer.Client;
using System;

using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Lucene.Server.Client
{
    public class QueryClient
    {
        private readonly string _path = "/client/wrapper";
        private readonly string _url;
        private readonly string _app;
        private readonly string _secret;

        public QueryClient(string url, string app, string secret)
        {
            _app = app;
            _secret = secret;
            _url = url + _path;
        }

        public async Task<string> Request(ClientWrapper wrapper)
        {
            return await DoPost(_url, wrapper.Build());
        }

        /// <summary>
        /// POST 请求
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="jsonData">JSON 数据</param>
        /// <returns>响应字符串</returns>
        public async  Task<string> DoPost(string url, string jsonData)
        {
            HttpClient client = new HttpClient();
            StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

            // 创建头部鉴权
            long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            string sign = GenerateMD5(_app + _secret + timestamp);
            client.DefaultRequestHeaders.Add("timestamp", timestamp.ToString());
            client.DefaultRequestHeaders.Add("app", _app);
            client.DefaultRequestHeaders.Add("sign", sign); 
             
            try
            { 
                HttpResponseMessage response =  await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    return response.Content.ReadAsStringAsync().Result;
                }
                else
                { 
                    return "{\"success\":false,\"message\":\"" + response.ReasonPhrase + "\",\"code\":500,\"result\":null,\"timestamp\":0}";
                }
            }
            catch (Exception ex) {
                return "{\"success\":false,\"message\":\"" + ex.Message + "\",\"code\":500,\"result\":null,\"timestamp\":0}";

            } 
        }

        /// <summary>
        /// 生成一个32位的MD5哈希值（十六进制字符串形式）
        /// </summary>
        /// <param name="input">输入字符串</param>
        /// <returns>MD5哈希值的十六进制字符串</returns>
        public static string GenerateMD5(string input)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] inputBytes = Encoding.UTF8.GetBytes(input);
                byte[] hashBytes = md5.ComputeHash(inputBytes);
                StringBuilder sb = new StringBuilder();
                foreach (byte b in hashBytes)
                {
                    sb.Append(b.ToString("x2"));
                }
                return sb.ToString();
            }
        }
    }
}